<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 *取消订单
 */
class CancleOrder extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('cancle_order')
            ->setDescription('10分钟取消订单');
    }

    //先写定时任务，后期用户量多了改队列
    protected function execute(Input $input, Output $output)
    {
        $cursor = Db::name('order')->where('status', 1)->where('expire_time', '>', 0)->where('expire_time', '<', time())->where('order_type', 1)->cursor();
        foreach ($cursor as $user) {
            Db::startTrans();
            try {
                Db::name('order')->where('id', $user['id'])->update(['status' => -1]);
                $orderItem = Db::name('order_item')->where('order_id', $user['id'])->select();
                foreach ($orderItem as $k => $v) {
                    if ($v['sku_id']) {
                        Db::name('goods_item')->where('id', $v['sku_id'])->inc('stock', $v['buy_num'])->update();
                    } else {
                        Db::name('goods')->where('id', $v['sku_id'])->inc('stock', $v['buy_num'])->update();
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }

        }
    }
}
